package com.example.demo.controller.wx;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.FileUtil;
import com.example.demo.util.RestRequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author ChenXU
 * @version 1.0
 * @createTime 2020-09-23 16:07
 * @description
 */
@RestController
@RequestMapping("/")
public class AnswerSheetController {
    @Value("${test.rootPath}")
    private String rootPath;
    @Value("${test.projectDir}")
    private String projectDir;
    private Logger logger = LoggerFactory.getLogger(AnswerSheetController.class);

    /***
     * 答题卡
     * @param picture
     * @return
     */
    @RequestMapping("answerSheet")
    public JSONObject answerSheet(@RequestParam(value = "picture") MultipartFile picture) {
        String fileUrl = FileUtil.uploadFile(picture, rootPath, projectDir,
                "answerSheet", "answerSheet");
        String pictureUrl = rootPath + fileUrl;
        JSONObject result = formDataMethod(pictureUrl);
        if (!result.get("code").equals(0)) {
            result = new JSONObject();
            result.put("result", "结果错误！");
        }
        return result;
    }

    //我记得转发form -data请求好像不行
    private JSONObject formDataMethod(String picture) {
        String url = "http://49.232.94.107:6001/upimg";
        RestTemplate restTemplate = new RestTemplate();
        FileSystemResource resource = new FileSystemResource(new File(picture));
        MultiValueMap entityByMultiForm = RestRequestUtil.getEntityByMultiForm();
        entityByMultiForm.add("img", resource);
//        entityByMultiForm.put("", new Object());
        JSONObject result = restTemplate.postForObject(url, entityByMultiForm, JSONObject.class);
        logger.info("识别返回数据{}", result.toJSONString());
        return result;
    }
}
